﻿using System;
using System.Linq;
using System.Web.Mvc;
using NBlog.Web.Application.Service;

namespace NBlog.Web.Application.Infrastructure
{
    public class LayoutController : Controller
    {
        protected readonly IServices Services;
        
        public LayoutController(IServices services)
        {
            Services = services;
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            string hostname = Request.Headers["HOST"];
            if (hostname.Contains("www."))
            {
                filterContext.Result = RedirectPermanent(Request.Url.ToString().Replace("www.", string.Empty));
                return;
            }

            base.OnActionExecuted(filterContext);

            var viewResult = filterContext.Result as ViewResultBase;
            if (viewResult == null) return;

            if (viewResult.ViewData.Model == null)
                viewResult.ViewData.Model = new LayoutModel();

            if (!(viewResult.ViewData.Model is LayoutModel))
                throw new InvalidCastException("View model must inherit LayoutModel in action: " + filterContext.ActionDescriptor.ActionName);

            var model = (LayoutModel)viewResult.ViewData.Model;
            InitialiseBaseViewModel(model);
        }

        private void InitialiseBaseViewModel(LayoutModel model)
        {
            model.Config = Services.Config.Current;
            model.Theme = Services.Theme.Current;
            var articles = Services.Article.GetList();
            var recentArticles = articles.OrderByDescending(p => p.DateCreated);
            var recentReviews = Services.Review.GetList().OrderByDescending(p => p.DateCreated);

            var stats = Services.Stats.GetList().ToList();
            var popularSlugs = stats.OrderByDescending(stat => stat.Views).Take(7).Select(s => s.Slug).ToList();
            var popularArticles = popularSlugs.Select(slug => articles.Find(s => s.Slug.Equals(slug))).Where(entity => entity != null).ToList();

            model.RecentPages = new SideBarBlockModel();
            model.RecentPages.Title = "Recent Articles";
            model.RecentPages.Entries = recentArticles.AsEntrySummaryModels();

            model.RecentReviews = new SideBarBlockModel();
            model.RecentReviews.Title = "Recent Elliptical Reviews";
            model.RecentReviews.Entries = recentReviews.AsEntrySummaryModels();

            model.PopularEntries = new SideBarBlockModel();
            model.PopularEntries.Title = "Popular Elliptical Articles";
            model.PopularEntries.Entries = popularArticles.AsEntrySummaryModels();
        }
    }
}